<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>企业微信登录</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .login-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 40px;
            text-align: center;
            max-width: 400px;
            width: 90%;
        }
        
        .logo {
            width: 80px;
            height: 80px;
            background: #1aad19;
            border-radius: 50%;
            margin: 0 auto 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32px;
            color: white;
        }
        
        .title {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin-bottom: 10px;
        }
        
        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }
        
        .login-btn {
            background: #1aad19;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            margin-bottom: 20px;
        }
        
        .login-btn:hover {
            background: #179b16;
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(26, 173, 25, 0.3);
        }
        
        .login-btn:active {
            transform: translateY(0);
        }
        
        .loading {
            display: none;
            color: #666;
            font-size: 14px;
        }
        
        .error {
            color: #ff4d4f;
            font-size: 14px;
            margin-top: 10px;
            display: none;
        }
        
        .success {
            color: #52c41a;
            font-size: 14px;
            margin-top: 10px;
            display: none;
        }
        
        .footer {
            margin-top: 30px;
            color: #999;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">企</div>
        <h1 class="title">企业微信登录</h1>
        <p class="subtitle">请使用企业微信扫码或点击下方按钮进行授权登录</p>
        
        <button class="login-btn" onclick="startWechatLogin()">
            授权企业微信登录
        </button>
        
        <div class="loading" id="loading">
            正在跳转到企业微信授权页面...
        </div>
        
        <div class="error" id="error"></div>
        <div class="success" id="success"></div>
        
        <div class="footer">
            <p>© 2024 企业微信登录系统</p>
        </div>
    </div>

    <script>
        // 配置信息 - 需要根据实际情况修改
        const CONFIG = {
            // 企业微信应用配置
            corpId: 'wweb2e9977cf9d5076', // 企业ID
            agentId: '1000019', // 应用ID
            redirectUri: encodeURIComponent(window.location.origin + '/login.html'), // 回调地址
            // 后端接口地址
            // backendUrl: 'YOUR_BACKEND_URL', // 后端服务地址
        };

        /**
         * 开始企业微信登录
         */
        function startWechatLogin() {
            const btn = document.querySelector('.login-btn');
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            const success = document.getElementById('success');
            
            // 隐藏之前的消息
            error.style.display = 'none';
            success.style.display = 'none';
            
            // 检查是否在企业微信环境
            if (isInWechatWork()) {
                // 在企业微信内，直接跳转授权
                redirectToWechatAuth();
            } else {
                // 不在企业微信内，显示提示
                showError('请在企业微信内打开此页面进行登录');
            }
        }

        /**
         * 检查是否在企业微信环境
         */
        function isInWechatWork() {
            const ua = navigator.userAgent.toLowerCase();
            return ua.includes('wxwork') || ua.includes('micromessenger');
        }

        /**
         * 跳转到企业微信授权页面
         */
        function redirectToWechatAuth() {
            const loading = document.getElementById('loading');
            const btn = document.querySelector('.login-btn');
            
            // 显示加载状态
            btn.style.display = 'none';
            loading.style.display = 'block';
            
            // 构造企业微信授权URL
            const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?` +
                `appid=${CONFIG.corpId}&` +
                `redirect_uri=${CONFIG.redirectUri}&` +
                `response_type=code&` +
                `scope=snsapi_base&` +
                `agentid=${CONFIG.agentId}&` +
                `state=STATE#wechat_redirect`;
            
            // 跳转到企业微信授权页面
            window.location.href = authUrl;
        }

        /**
         * 显示错误信息
         */
        function showError(message) {
            const error = document.getElementById('error');
            error.textContent = message;
            error.style.display = 'block';
        }

        /**
         * 显示成功信息
         */
        function showSuccess(message) {
            const success = document.getElementById('success');
            success.textContent = message;
            success.style.display = 'block';
        }

        /**
         * 调用后端接口获取token
         */
        async function getTokenFromBackend(code) {
            try {
                const response = await fetch(`/api/sys/thirdLogin/oauth2/wechat_enterprise/callback?code=${code}&state=STATE`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await response.json();
                
                if (result.success) {
                    // 登录成功，保存token和用户信息（与项目保持一致）
                    localStorage.setItem('TOKEN__', result.result.token);
                    if (result.result.userInfo) {
                        localStorage.setItem('USER__INFO__', JSON.stringify(result.result.userInfo));
                    }
                    if (result.result.roles) {
                        localStorage.setItem('ROLES__KEY__', JSON.stringify(result.result.roles));
                    }
                    if (result.result.tenantid) {
                        localStorage.setItem('TENANT_ID', result.result.tenantid);
                    }
                    if (result.result.loginInfo) {
                        localStorage.setItem('LOGIN__INFO__', JSON.stringify(result.result.loginInfo));
                    }
                    
                    showSuccess('登录成功，正在跳转...');
                    
                    // 跳转到主页面
                    setTimeout(() => {
                        window.location.href = '/';
                    }, 1500);
                } else {
                    throw new Error(result.message || '登录失败');
                }
            } catch (error) {
                console.error('获取token失败:', error);
                showError('登录失败: ' + error.message);
            }
        }

        /**
         * 页面加载完成后检查URL参数
         */
        window.onload = function() {
            const urlParams = new URLSearchParams(window.location.search);
            const code = urlParams.get('code');
            const state = urlParams.get('state');
            
            if (code) {
                // 从企业微信授权回调，获取到code
                const loading = document.getElementById('loading');
                const btn = document.querySelector('.login-btn');
                
                btn.style.display = 'none';
                loading.textContent = '正在获取登录信息...';
                loading.style.display = 'block';
                
                // 调用后端接口获取token
                getTokenFromBackend(code);
            }
        };

        // 添加一些交互效果
        document.addEventListener('DOMContentLoaded', function() {
            const btn = document.querySelector('.login-btn');
            
            btn.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-2px)';
            });
            
            btn.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0)';
            });
        });
    </script>
</body>
</html>